package com.ailot.cloud.base.log.utils;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.ailot.cloud.base.log.entity.SysLog;
import com.ailot.cloud.base.security.utils.SecurityUtil;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 组装操作日志
 * 通过UtilityClass来标记为静态方法类
 *
 * @author
 */
@UtilityClass
public class SysLogUtil {
    public SysLog AssembleSysLog() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        SysLog sysLog = new SysLog();
        sysLog.setCreateUser(getUsername());
        sysLog.setCreateId(getUserId());
        sysLog.setIpAddress(ServletUtil.getClientIP(request));
        sysLog.setRequestUri(request.getRequestURI());
        sysLog.setMethod(request.getMethod());
        sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
        return sysLog;
    }


    /**
     * 获取用户ID
     */
    private String getUserId() {
        return SecurityUtil.getId();
    }

    /**
     * 获取用户名称
     */
    private String getUsername() {
        return SecurityUtil.getUsername();
    }

}
